package com.item.mofan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.item.mofan.common.Result;
import com.item.mofan.entity.User;
import com.item.mofan.service.UserService;
import com.item.mofan.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user,HttpServletRequest request){
        //获取手机号
        String phone=user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //生成4位随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
//            request.getSession().setAttribute(phone,code);
            //redis缓存验证码存活时间1分钟
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
            return Result.success("短信发送成功");
        }
      return Result.error("短信发送失败");
    }
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        String phone=map.get("phone").toString();
        String code=map.get("code").toString();
//        Object codeInSession = session.getAttribute(phone);
        //获取redis储存的值
        Object codeInSession=redisTemplate.opsForValue().get(phone);
        if (codeInSession==null){
            return Result.error("验证码已过期");
        }
        //比对验证码
        if (code!=null&&codeInSession.equals(code)){
            //判断是否为新用户
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotEmpty(phone),User::getPhone,phone);
            User user=userService.getOne(queryWrapper);

            //如果为新用户，自动注册
            if (user==null){
                user=new User();
                user.setName("用户");
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }
    @PostMapping("/loginout")
    public Result<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return Result.success("退出成功");
    }
}
